package pl.mdziedzic.unittests;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumBase {

	protected static WebDriver driver;
	protected String baseUrl;
	protected StringBuffer verificationErrors = new StringBuffer();
	protected static final Integer timeOut = 15;


	public void setUp(String mainLink) throws Exception {
		driver = new FirefoxDriver();
		baseUrl = mainLink;
		driver.manage().timeouts().implicitlyWait(timeOut, TimeUnit.SECONDS);
	}
	
	@After
	public void tearDown() throws Exception {
		driver.quit();
	}

	public void clickLinkByText(String link) {
		driver.findElement(By.linkText(link)).click();
	}

	protected void checkSiteTitle(String title) throws InterruptedException {
		for (int second = 0;; second++) {
			if (second >= timeOut) fail("timeout");
			try { 
				if (title.equals(driver.getTitle())) break; 
			} 
			catch (Exception e) {
					
			}
			Thread.sleep(1000);
		}
	}

	protected void openMainPage() {
		driver.get(baseUrl + "/");
	}

	public SeleniumBase() {
		super();
	}
	
	protected Integer createItemNum() {
		return 1000+new Random().nextInt(100000);
	}
	
	protected void waitForElement(final By identifier) {
		WebDriverWait wait = new WebDriverWait(driver, 5);
//		wait.until(new Function())
	}
	
	protected boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
	
	protected void shouldCheck2ndMenuPosition() {
		try {
			assertTrue(isElementPresent(By.xpath("//div[@id='menu_vert']/ul/li[2]/a")));
		} catch (Error e) {
			verificationErrors.append(e.toString());
		}
	}

	public void selectElementFromList(String listId, String elementName) {
		WebElement e = driver.findElement(By.id(listId));
		Select s = new Select(e);
		s.selectByVisibleText(elementName);
	}
}